import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableData'
import { getProductClassConfigByType } from '@/api/goods'
import {
  getDelayDaysConfigList,
  importDelayDaysConfig,
  delayDaysConfigConfigExportExcel,
  delayDaysConfigUpdateConfig,
} from '@/api/reorder'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useLatestColumns } from '../columns'
import { ReorderCategoryDelayDaysConfigVO } from '../types'
import CustomTable from '@/components/CustomTable'
import { SearchForm } from '@/components/CustomForm'
import './Latest.less'
import { useAppSelector } from '@/store/hooks'
import PermissionButton from '@/components/PermissionButton'
import { ImportOutlined, UploadOutlined } from '@ant-design/icons'
import ImportFileModal from '@/components/ImportFileModal'
import { exportNotification, importNotification } from '@/utils/util'
import { DatePicker, Form, message, Modal, Spin } from 'antd'
import { useNavigate } from 'react-router-dom'
import { IMPORT_FILE_ENUM } from '@/constant'
import dayjs from 'dayjs'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [exportLoading, setexportLoading] = useState(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [timeModalShow, settimeModalShow] = useState<boolean>(false)
  const [spinning, setspinning] = useState<boolean>(false)
  const [CurrentInfo, setCurrentInfo] = useState<ReorderCategoryDelayDaysConfigVO>({})
  const [tableData, settableData] = useState<ReorderCategoryDelayDaysConfigVO[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [FormSend] = useForm()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ReorderCategoryDelayDaysConfigVO>(
    getDelayDaysConfigList,
    {
      form: form,
      immediatelySend: false,
    },
  )
  useEffect(() => {
    getProductClassConfig()
    search({
      ...params,
    })
  }, [])
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.className,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await importDelayDaysConfig<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const handleExport = async () => {
    setexportLoading(true)
    setspinning(true)
    const res = await delayDaysConfigConfigExportExcel({
      ...params,
    })
      .catch(() => setspinning(false))
      .finally(() => {
        setexportLoading(false)
      })
    if (res?.code === 200 && res?.data) {
      await exportNotification(res?.data, navigate).finally(() => setspinning(false))
    }
  }
  const onSave = async (info: ReorderCategoryDelayDaysConfigVO) => {
    const res = await delayDaysConfigUpdateConfig({
      id: info.id,
      delayDayNum: info?.delayDayNum || 0,
    }).finally(() => search(params))
    if (res.code === 200) {
      message.success('操作成功')
    }
  }
  const reLoadPage = () => {
    search(params)
  }
  const onModalCancel = () => {
    settimeModalShow(false)
    FormSend.resetFields()
  }
  const onSendOk = async () => {
    const data = await FormSend.validateFields()
    const res = await delayDaysConfigUpdateConfig({
      id: CurrentInfo.id,
      lastDay: dayjs(data.lastDay).format('YYYY-MM-DD'),
    })
    if (res.code === 200) {
      onModalCancel()
      reLoadPage()
      message.success('操作成功')
    }
  }
  return (
    <PageContainer className="goods_sizeconfig_page">
      <SearchForm
        className="reorder_latest"
        params={params}
        form={form}
        searchConfig={[
          {
            name: 'productYear',
            label: '年份',
            type: 'DatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
            },
          },
          { label: '大类', name: 'largeClassName', type: 'Select', option: classBig },
          {
            name: 'seasonClassifyName',
            label: '季节分组',
            type: 'Select',
            option: DICTDATA.season_classify,
            placeholder: '请选择季节分组',
            config: {
              optionFilterProp: 'label',
            },
          },
          {
            label: '是否维护最晚到货时间',
            name: 'lastDayConfigFlag',
            type: 'Select',
            option: [
              { label: '是', value: true },
              { label: '否', value: false },
            ],
          },
          {
            label: '是否维护到货异常天数',
            name: 'delayDayConfigFlag',
            type: 'Select',
            option: [
              { label: '是', value: true },
              { label: '否', value: false },
            ],
          },
        ]}
        onFinish={(vals: any) => {
          search({
            ...vals,
            productYear: vals.productYear ? dayjs(vals.productYear).format('YYYY') : null,
          })
        }}
        onReset={() => {
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                icon={<ImportOutlined />}
                permission="latestBatchImport"
                onClick={() => setisUploadFileShow(true)}
              >
                批量导入配置
              </PermissionButton>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="latestExport"
                icon={<UploadOutlined />}
                loading={exportLoading}
                onClick={handleExport}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        columns={useLatestColumns({
          tableData,
          settableData,
          onSave,
          reLoadPage,
          settimeModalShow,
          setCurrentInfo,
          canEdit: buttonCodeList?.includes('latestBatchImport'),
        })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        extraHeight={28}
        isScrollY
        filterDomClassName={'reorder_latest'}
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.LATEST_IMPORT}
      ></ImportFileModal>
      <Modal title="最晚到货时间" open={timeModalShow} onCancel={onModalCancel} onOk={onSendOk}>
        <Form form={FormSend} layout="vertical" initialValues={{ lastDay: dayjs() }}>
          <Form.Item
            label="最晚到货时间"
            name="lastDay"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择最晚到货时间',
              },
            ]}
          >
            <DatePicker></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
